import { invoke } from '@tauri-apps/api';
import { listen } from '@tauri-apps/api/event';

// 定义包信息类型
export interface PackageInfo {
  name: string;
  version: string;
  summary?: string;
  location?: string;
}

// 定义操作日志类型
export interface OperationLog {
  id: number;
  timestamp: string;
  operation_type: string;
  package_spec: string;
  command: string;
  success: boolean;
  output: string;
  error_message: string;
}

// 获取已安装的包列表
export const getInstalledPackages = async (): Promise<PackageInfo[]> => {
  try {
    // 调用Rust后端命令
    const packages = await invoke<PackageInfo[]>('get_installed_packages');
    return packages;
  } catch (error) {
    console.error('获取包列表失败:', error);
    // 返回模拟数据，以便在开发环境中能够正常显示
    return [
      { name: 'requests', version: '2.31.0', summary: 'Python HTTP for Humans.' },
      { name: 'pandas', version: '2.1.4', summary: 'Powerful data structures for data analysis.' },
      { name: 'numpy', version: '1.26.3', summary: 'NumPy is the fundamental package for array computing.' },
      { name: 'matplotlib', version: '3.8.2', summary: 'Python plotting package.' },
      { name: 'scikit-learn', version: '1.3.2', summary: 'Machine learning in Python.' },
    ];
  }
};

// 执行pip命令的回调函数类型
export interface PipCommandCallbacks {
  onProgress?: (line: string) => void;
  onComplete?: (success: boolean, output: string) => void;
}

// 执行pip命令（安装、卸载、更新）
export const runPipCommand = async (
  operationType: 'install' | 'uninstall' | 'update',
  packageSpec: string,
  callbacks?: PipCommandCallbacks
): Promise<void> => {
  try {
    // 监听进度事件
    const unlisten = await listen('pip-progress', (event) => {
      const line = event.payload as string;
      callbacks?.onProgress?.(line);
    });

    // 调用Rust后端命令执行pip操作
    const output = await invoke<string>('run_pip_command', {
      operationType,
      packageSpec
    });

    // 取消监听进度事件
    unlisten();
    
    // 通知完成
    callbacks?.onComplete?.(true, output);
  } catch (error) {
    console.error(`${operationType}包失败:`, error);
    // 取消监听进度事件
    const unlisten = await listen('pip-progress', () => {});
    unlisten();
    
    // 通知失败
    callbacks?.onComplete?.(false, error instanceof Error ? error.message : '未知错误');
  }
};

// 获取操作日志
export const getOperationLogs = async (): Promise<OperationLog[]> => {
  try {
    // 调用Rust后端命令
    const logs = await invoke<OperationLog[]>('get_operation_logs');
    return logs;
  } catch (error) {
    console.error('获取日志失败:', error);
    // 返回模拟数据
    return [
      {
        id: 1,
        timestamp: '2024-01-10 14:30:45',
        operation_type: 'install',
        package_spec: 'requests',
        command: 'pip install requests',
        success: true,
        output: 'Successfully installed requests-2.31.0',
        error_message: ''
      },
      {
        id: 2,
        timestamp: '2024-01-10 14:25:12',
        operation_type: 'uninstall',
        package_spec: 'oldpackage',
        command: 'pip uninstall oldpackage -y',
        success: true,
        output: 'Successfully uninstalled oldpackage-1.0.0',
        error_message: ''
      },
      {
        id: 3,
        timestamp: '2024-01-10 14:20:33',
        operation_type: 'update',
        package_spec: 'pandas',
        command: 'pip install -U pandas',
        success: false,
        output: 'Collecting pandas...',
        error_message: 'Network error: could not connect to PyPI'
      }
    ];
  }
};